<!--
 * @Author: 梁青春
 * @Date: 2025-11-03 12:00:00
 * @LastEditTime: 2025-11-19 10:53:08
 * @LastEditors: 梁青春
 * @Description: 新增病区页面
-->
<template>
  <div class="main-container ward-add-form">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">新增病区</h2>
      </div>
      <div class="header-right">
        <el-button icon="ArrowLeft" @click="handleBack" class="default-btn op-btn"> 返回 </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading" class="add-btn op-btn">
          保存
        </el-button>
      </div>
    </div>

    <!-- 病区信息表单 -->
    <div class="form-container">
      <el-card class="form-card">
        <template #header>
          <span class="card-title">病区信息</span>
        </template>

        <el-form ref="wardFormRef" :model="wardForm" :rules="wardRules" label-width="120px" class="ward-form">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="病区名称" prop="wardName">
                <el-input
                  v-model="wardForm.wardName"
                  placeholder="请输入病区名称"
                  maxlength="50"
                  show-word-limit
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="病区位置" prop="wardLocation">
                <el-input
                  v-model="wardForm.wardLocation"
                  placeholder="请输入病区位置"
                  maxlength="100"
                  show-word-limit
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="科室类别" prop="relatedDepartments">
                <el-select
                  v-model="selectedDepartments"
                  multiple
                  placeholder="请选择科室名称"
                  style="width: 100%"
                  collapse-tags
                  collapse-tags-tooltip
                  clearable
                >
                  <el-option
                    v-for="dept in departmentOptions"
                    :key="dept.deptId"
                    :label="dept.deptName"
                    :value="dept.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="section-title">病区成员</div>
          <div class="member-section">
            <div class="member-header">
              <span class="member-label">病区成员</span>
            </div>

            <!-- 未选择成员时的默认状态 -->
            <div v-if="selectedMembers.length === 0" class="member-empty-state" @click="handleOpenMemberDialog">
              <div class="empty-icon">
                <el-icon size="48" color="#c0c4cc">
                  <User />
                </el-icon>
              </div>
              <div class="empty-text">
                <p class="empty-title">暂未选择病区成员</p>
                <p class="empty-desc">选择科室后点击添加选择病区成员</p>
              </div>
            </div>

            <!-- 已选择成员的展示状态 -->
            <div v-else class="selected-members">
              <div class="selected-header">
                <span class="selected-count">已选 {{ selectedMembers.length }} 项</span>
              </div>
              <div class="selected-list-container">
                <div class="selected-list">
                  <div v-for="member in selectedMembers" :key="member.userId" class="selected-member-tag">
                    <div class="member-avatar">
                      <el-icon size="16" color="#409eff">
                        <UserFilled />
                      </el-icon>
                    </div>
                    <div class="member-info">
                      <div class="member-name">{{ member.nickName }}</div>
                      <div class="member-details">{{ member.dept?.deptName }}</div>
                    </div>
                    <div class="remove-btn" @click="handleRemoveSelectedMember(member.userId)">
                      <el-icon size="12" color="#f56c6c">
                        <Close />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </div>
              <div class="add-more-section">
                <el-button type="primary" plain size="small" @click="handleOpenMemberDialog" class="add-more-btn">
                  <el-icon><Plus /></el-icon>
                  添加
                </el-button>
              </div>
            </div>
          </div>

          <!-- 成员选择弹窗（组件化） -->
          <MemberSelectDialog
            v-model="memberDialogVisible"
            :members="memberList"
            :initialSelected="selectedMembers"
            :loading="memberListLoading"
            @search="onMemberDialogSearch"
            @confirm="onMemberDialogConfirm"
            @cancel="onMemberDialogCancel"
          />

          <div class="section-title">病区病床</div>
          <div class="bed-section">
            <!-- 病床表格 -->
            <el-table :data="wardForm.beds" border class="bed-table">
              <el-table-column prop="roomName" label="房间名称" width="160" align="center">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.roomName"
                    placeholder="请输入"
                    size="small"
                    @input="validateBedData(scope.$index)"
                  />
                </template>
              </el-table-column>

              <el-table-column prop="bedCount" label="床位数" width="120" align="center">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.bedCount"
                    placeholder="请输入床位数"
                    size="small"
                    style="width: 100%"
                    maxlength="2"
                    @input="onBedCountInput(scope.$index, $event)"
                  />
                </template>
              </el-table-column>

              <el-table-column
                prop="bedNos"
                label="床号"
                align="center"
                min-width="200"
                max-width="320"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <div class="bed-numbers-display">
                    <span v-if="!scope.row.bedNos || scope.row.bedNos.length === 0" class="empty-bed-numbers">
                      请先输入床位数
                    </span>
                    <template v-else>
                      <BedNoEditDialog
                        :bedCount="scope.row.bedCount || 0"
                        :initialSelected="scope.row.bedNos || []"
                        :usedNumbers="Array.from(getAllUsedBedNumbers(scope.$index))"
                        @confirm="onBedNosPopConfirm(scope.$index, $event)"
                      >
                        <template #reference>
                          <div
                            class="bed-numbers-display hover-editable"
                            :class="{ overflow: scope.row.bedNos && scope.row.bedNos.length > 3 }"
                            :title="scope.row.bedNos && scope.row.bedNos.length > 0 ? scope.row.bedNos.join(', ') : ''"
                          >
                            <el-tag
                              v-for="bedNum in scope.row.bedNos"
                              :key="bedNum"
                              size="small"
                              class="bed-number-tag"
                              type="success"
                            >
                              {{ bedNum }}
                            </el-tag>
                          </div>
                        </template>
                      </BedNoEditDialog>
                    </template>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="admissionRestriction" label="入住限定" width="200" align="center">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.admissionRestriction"
                    placeholder="请选择"
                    size="small"
                    @change="validateBedData(scope.$index)"
                  >
                    <el-option
                      v-for="dict in sys_stay_restrictions"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column prop="chargeItems" label="收费项目(入院后每日自动计费)" min-width="250" align="center">
                <template #default="scope">
                  <div class="charge-items-cell hover-editable" @click="openChargeItemDialog(scope.$index)">
                    <div v-if="scope.row.treatments && scope.row.treatments.length > 0" class="selected-items">
                      <el-tag v-for="item in scope.row.treatments" :key="item.id" size="small" class="charge-item-tag">
                        {{ item.treatmentName }}
                      </el-tag>
                    </div>
                    <div v-else class="empty-state">
                      <span class="empty-text">点击选择收费项目</span>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="chargeAmount" label="总额" width="100" align="center">
                <template #default="scope">
                  <span class="total-amount">¥{{ scope.row.chargeAmount }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="remark" label="备注" width="120" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="请输入" size="small" />
                </template>
              </el-table-column>

              <el-table-column width="60" align="center" fixed="right" class-name="no-ellipsis">
                <template #default="scope">
                  <el-button
                    type="danger"
                    icon="CloseBold"
                    size="small"
                    @click="handleRemoveBed(scope.$index)"
                    class="remove-btn"
                    :disabled="wardForm.beds.length <= 1"
                  />
                </template>
              </el-table-column>
            </el-table>

            <!-- 添加病床按钮 -->
            <div class="add-bed-section">
              <el-button type="primary" @click="handleAddRoom" class="add-bed-btn">
                <el-icon><Plus /></el-icon>
                添加
              </el-button>
            </div>
          </div>

          <!-- 收费项目选择弹窗（组件化） -->
          <ChargeItemBatchDialog
            v-model="chargeItemDialogVisible"
            :items="chargeItemList"
            :initialSelected="wardForm.beds[currentBedIndex]?.treatments || []"
            :loading="chargeItemListLoading"
            @search="onChargeItemDialogSearch"
            @confirm="onChargeItemDialogConfirm"
            @cancel="onChargeItemDialogCancel"
          />
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup name="WardAddForm">
import { ref, reactive, onMounted, getCurrentInstance, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { addWard, getDepartmentList, getWardDetail, updateWard } from '@/api/baseinfo/ward'
import { getChargeItemListNoPage } from '@/api/baseinfo/treatment'
import { listUserByDepts } from '@/api/system/user'
import mock from '@/mock/ward'
// 引入组件与工具函数
import MemberSelectDialog from './components/MemberSelectDialog.vue'
import ChargeItemBatchDialog from './components/ChargeItemBatchDialog.vue'
import BedNoEditDialog from './components/BedNoEditDialog.vue'
import { calculateTotalAmount } from './components/utils/chargeItemUtils'

const proxy = getCurrentInstance().proxy
const router = useRouter()
const route = useRoute()
const { sys_stay_restrictions } = proxy.useDict('sys_stay_restrictions')
// 响应式数据
const submitLoading = ref(false)
const wardFormRef = ref(null)
const selectedDepartments = ref([])
const departmentOptions = ref([])

// 床位数选项 (01-40)
const bedCountOptions = ref(Array.from({ length: 40 }, (_, i) => i + 1))

// 成员选择相关数据
const memberDialogVisible = ref(false)
const memberListLoading = ref(false)
const memberList = ref([])
let memberListLocal = []
const selectedMembers = ref([])

// 收费项目选择相关数据
const chargeItemDialogVisible = ref(false)
const chargeItemListLoading = ref(false)
const chargeItemList = ref([])
const currentBedIndex = ref(-1)

// 表单数据
const wardForm = reactive({
  wardName: '',
  wardLocation: '',
  relatedDepartments: '',
  beds: [
    {
      roomName: '',
      bedCount: null, // 改为null，等待用户选择
      bedNos: [], // 改为数组存储生成的床号
      admissionRestriction: '1',
      treatments: [],
      chargeAmount: '0.00',
      remark: ''
    }
  ]
})

// 表单验证规则
const wardRules = {
  wardName: [
    { required: true, message: '请输入病区名称', trigger: 'blur' },
    { min: 2, max: 50, message: '病区名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  wardLocation: [
    { required: true, message: '请输入病区位置', trigger: 'blur' },
    { min: 2, max: 100, message: '病区位置长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  relatedDepartments: [{ required: true, message: '请选择关联科室', trigger: 'change' }]
}

// 方法定义
const loadDepartmentList = async () => {
  try {
    const response = await getDepartmentList({ deptType: 4 })
    if (response.code === 200) {
      departmentOptions.value = response.data
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
  }
}

// 加载成员列表（支持关键字参数）
const loadMemberList = async () => {
  if (!wardForm.relatedDepartments) {
    proxy.$modal.notifyWarning('请选择关联科室')
    return
  }
  try {
    const ids = wardForm.relatedDepartments
    memberListLoading.value = true
    const response = await listUserByDepts(ids)
    if (response.code === 200) {
      memberList.value = response.data
      memberListLocal = response.data
      memberDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取成员列表失败:', error)
  } finally {
    memberListLoading.value = false
  }
}

// 本地搜索成员列表
const localSearchMemberList = keyword => {
  if (!keyword) {
    memberList.value = memberListLocal
    return
  }
  memberList.value = memberListLocal.filter(item => item.userName.includes(keyword))
}

// 打开成员选择弹窗
const handleOpenMemberDialog = async () => {
  await loadMemberList()
}

// 成员弹窗事件：搜索/确认/取消
const onMemberDialogSearch = keyword => {
  localSearchMemberList(keyword)
}
const onMemberDialogConfirm = list => {
  selectedMembers.value = [...list]
  memberDialogVisible.value = false
}
const onMemberDialogCancel = () => {
  memberDialogVisible.value = false
}

// 移除已选择的成员
const handleRemoveSelectedMember = memberId => {
  selectedMembers.value = selectedMembers.value.filter(m => m.userId !== memberId)
}

// 加载收费项目列表（支持关键字参数）
const loadChargeItemList = async (keyWord = '') => {
  try {
    chargeItemListLoading.value = true
    const response = await getChargeItemListNoPage({ keyWord, isInpDoctor: 1, page: 1, pageSize: 100 })
    if (response.code === 200) {
      chargeItemList.value = response.data
    }
  } catch (error) {
    console.error('获取收费项目列表失败:', error)
  } finally {
    chargeItemListLoading.value = false
  }
}

// 打开收费项目选择弹窗
const openChargeItemDialog = async bedIndex => {
  console.log('openChargeItemDialog called with bedIndex:', bedIndex) // 调试信息

  currentBedIndex.value = bedIndex
  chargeItemDialogVisible.value = true

  await loadChargeItemList()
}
// 收费弹窗事件：搜索/确认/取消
const onChargeItemDialogSearch = keyword => {
  // 通过keyword自动过滤列表不调接口，清空输入后还原列表
  loadChargeItemList(keyword)
}
const onChargeItemDialogConfirm = list => {
  if (currentBedIndex.value >= 0) {
    const currentBed = wardForm.beds[currentBedIndex.value]
    currentBed.treatments = [...list]
    currentBed.chargeAmount = calculateTotalAmount(list).toFixed(2)
  }
  chargeItemDialogVisible.value = false
  currentBedIndex.value = -1
}
const onChargeItemDialogCancel = () => {
  chargeItemDialogVisible.value = false
  currentBedIndex.value = -1
}

// 床位数变化处理：按病区全局唯一顺序生成床号
const handleBedCountChange = bedIndex => {
  const bed = wardForm.beds[bedIndex]
  const bedCount = bed.bedCount

  const currentNos = Array.isArray(bed.bedNos) ? bed.bedNos : []
  const existingCount = currentNos.length

  if (!bedCount || bedCount <= 0) {
    bed.bedNos = []
  } else if (!bed.roomId) {
    // 新增/未落库房间：保持原有自动生成逻辑，避免影响既有流程
    bed.bedNos = generateUniqueBedNos(bedCount, bedIndex)
  } else {
    // 已存在的房间（有 roomId）：只允许增加，不允许减少
    if (bedCount < existingCount) {
      proxy.$modal.notifyWarning('已建病房不可减少床位数')
      bed.bedCount = existingCount
      // 不修改 bedNos，直接返回
    } else if (bedCount === existingCount) {
      // 不变：保留现有床号
    } else {
      // 增加：按病区最大床号递增补充
      let max = getGlobalMaxBedNumber()
      const needAppend = bedCount - existingCount
      for (let i = 0; i < needAppend; i++) {
        max += 1
        currentNos.push(formatBedNumber(max))
      }
      bed.bedNos = currentNos
    }
  }

  if (bed.treatments && bed.treatments.length > 0) {
    bed.chargeAmount = calculateTotalAmount(bed.treatments).toFixed(2)
  }

  validateBedData(bedIndex)
}

// 文本输入实时校验：仅保留正整数，范围 1-40，并驱动床号生成
const onBedCountInput = (bedIndex, val) => {
  const raw = String(val ?? '')
  // 仅保留数字字符
  const digits = raw.replace(/\D+/g, '')
  let num = digits ? parseInt(digits, 10) : null
  if (num != null) {
    if (!Number.isFinite(num)) num = null
    // else {
    //   if (num < 1) num = 1
    //   if (num > 40) num = 40
    // }
  }
  // 更新为数值类型，避免字符串与数字比较造成校验异常
  wardForm.beds[bedIndex].bedCount = num

  // 有效数值时，触发原有变更逻辑；否则清空床号
  if (num != null && Number.isInteger(num) && num > 0) {
    handleBedCountChange(bedIndex)
  } else {
    wardForm.beds[bedIndex].bedNos = []
  }
}

// 验证病床数据
const validateBedData = bedIndex => {
  const bed = wardForm.beds[bedIndex]

  // 验证床位数是否选择
  if (!bed.bedCount || bed.bedCount <= 0) {
    console.warn(`第${bedIndex + 1}行：请选择床位数`)
    return false
  }

  // 验证房间名称是否填写
  if (!bed.roomName || bed.roomName.trim() === '') {
    console.warn(`第${bedIndex + 1}行：请填写房间名称`)
    return false
  }

  // 验证床号是否生成
  if (!bed.bedNos || bed.bedNos.length === 0) {
    console.warn(`第${bedIndex + 1}行：床号未生成，请重新选择床位数`)
    return false
  }

  // 验证床号数量是否与床位数匹配
  if (bed.bedNos.length !== bed.bedCount) {
    console.warn(`第${bedIndex + 1}行：床号数量与床位数不匹配`)
    return false
  }

  console.log('验证病床数据通过:', bed)
  return true
}

// ===================== 床号逻辑：唯一生成与编辑 =====================
// 提取床号的数字部分：支持 '01床' 或数字
const parseBedNumber = val => {
  if (val == null) return null
  if (typeof val === 'number') return val
  const num = String(val).replace(/床$/, '')
  const parsed = parseInt(num, 10)
  return Number.isNaN(parsed) ? null : parsed
}

// 格式化床号显示（两位数+“床”）
const formatBedNumber = n => `${String(n).padStart(2, '0')}床`

// 获取除指定行外的已使用床号集合
const getAllUsedBedNumbers = excludeIndex => {
  const set = new Set()
  wardForm.beds.forEach((b, idx) => {
    if (excludeIndex != null && idx === excludeIndex) return
    ;(b.bedNos || []).forEach(no => {
      const num = parseBedNumber(no)
      if (num != null) set.add(num)
    })
  })
  return set
}

// 获取病区内已使用的最大床号（数字），若不存在则返回 0
const getGlobalMaxBedNumber = () => {
  let max = 0
  wardForm.beds.forEach(b => {
    ;(b.bedNos || []).forEach(no => {
      const n = parseBedNumber(no)
      if (n != null && n > max) max = n
    })
  })
  return max
}

// 生成指定数量的唯一床号（顺序递增，跨房间不重复）
const generateUniqueBedNos = (count, bedIndex) => {
  const used = getAllUsedBedNumbers(bedIndex)
  const result = []
  let cur = 1
  while (used.has(cur)) cur++
  for (let i = 0; i < count; i++) {
    while (used.has(cur)) cur++
    result.push(formatBedNumber(cur))
    used.add(cur)
    cur++
  }
  return result
}

// Popconfirm 确认床号：按行更新并校验跨房间唯一
const onBedNosPopConfirm = (bedIndex, numbers) => {
  const used = getAllUsedBedNumbers(bedIndex)
  const localSet = new Set(numbers)
  if (localSet.size !== numbers.length) {
    proxy.$modal.notifyWarning('当前房间内床号存在重复，请修改')
    return
  }
  for (const n of numbers) {
    if (used.has(n)) {
      proxy.$modal.notifyWarning(`床号 ${n} 与其他房间冲突，请调整`)
      return
    }
  }
  wardForm.beds[bedIndex].bedNos = numbers.map(formatBedNumber)
}

// 提交前校验所有床号唯一
const validateUniqueBedNos = () => {
  const set = new Set()
  for (let i = 0; i < wardForm.beds.length; i++) {
    const nos = wardForm.beds[i].bedNos || []
    for (const no of nos) {
      const n = parseBedNumber(no)
      if (n == null) continue
      if (set.has(n)) return false
      set.add(n)
    }
  }
  return true
}

// 添加病房
const handleAddRoom = () => {
  const lastBed = wardForm.beds[wardForm.beds.length - 1]
  const newBed = {
    roomName: lastBed.roomName || '',
    bedCount: lastBed.bedCount || 0, // 新房间默认沿用上一个房间的床位数
    // 新房间的床号必须在病区范围内不重复：按唯一顺序生成
    bedNos: lastBed.bedCount && lastBed.bedCount > 0 ? generateUniqueBedNos(lastBed.bedCount, null) : [],
    admissionRestriction: lastBed.admissionRestriction || '1',
    treatments: lastBed.treatments ? [...lastBed.treatments] : [],
    chargeAmount: lastBed.chargeAmount || '0.00',
    remark: ''
  }
  wardForm.beds.push(newBed)
}

// 删除病床
const handleRemoveBed = index => {
  if (wardForm.beds.length <= 1) {
    proxy.$modal.notifyWarning('至少需要保留一条病床记录')
    return
  }
  wardForm.beds.splice(index, 1)
}

const handleBack = () => {
  router.replace('/baseinfo/wardManagement')
}

const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await wardFormRef.value.validate()
    if (!valid) {
      return
    }

    // 验证科室选择
    if (selectedDepartments.value.length === 0) {
      proxy.$modal.notifyWarning('请选择关联科室')
      return
    }
    // 验证成员选择
    if (selectedMembers.value.length === 0) {
      proxy.$modal.notifyWarning('请选择关联成员')
      return
    }
    // 校验床号在整个病区内不可重复
    const uniqueOk = validateUniqueBedNos()
    if (!uniqueOk) {
      proxy.$modal.notifyWarning('床号在病区范围内不可重复，请检查床号设置')
      return
    }
    submitLoading.value = true
    // 准备提交数据
    const submitData = {
      baseWard: {
        wardId: wardForm.wardId ?? null,
        wardName: wardForm.wardName,
        wardLocation: wardForm.wardLocation
      },
      deptIds: selectedDepartments.value,
      users: selectedMembers.value,
      wardRooms: wardForm.beds
    }
    if (wardForm.wardId) {
      // 编辑病区
      const response = await updateWard(submitData)

      if (response.code === 200) {
        proxy.$modal.notifySuccess(response.message || '修改成功')
        router.replace('/baseinfo/wardManagement')
      } else {
        proxy.$modal.notifyWarning(response.message || '修改失败')
      }
    } else {
      // 新增病区
      const response = await addWard(submitData)

      if (response.code === 200) {
        proxy.$modal.notifySuccess(response.message || '新增成功')
        // 成功后返回列表页
        router.replace('/baseinfo/wardManagement')
      } else {
        proxy.$modal.notifyWarning(response.message || '新增失败')
      }
    }
  } catch (error) {
    console.error('新增病区失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadDepartmentList()
  // 如路由携带 wardId，则进入编辑模式并拉取详情进行数据回显
  initEditData()
})

// 监听科室选择变化
// 中文注释：监听科室选择变化——当移除某科室(deptId)时，自动移除该科室下的已选成员
watch(
  selectedDepartments,
  (newVal, oldVal) => {
    // 中文注释：同步字符串形式到表单字段，供后端提交
    wardForm.relatedDepartments = newVal.join(',')

    // 中文注释：计算被移除的科室ID列表
    const prev = Array.isArray(oldVal) ? oldVal : []
    const removedDeptIds = prev.filter(id => !newVal.includes(id))

    // 中文注释：如果确实移除了某些科室，则过滤掉这些科室的成员
    if (removedDeptIds.length > 0) {
      selectedMembers.value = selectedMembers.value.filter(m => {
        // 中文注释：兼容成员对象的不同字段结构：deptId 或 m.dept.deptId / m.dept.id
        const memberDeptId = m?.deptId ?? m?.dept?.deptId ?? m?.dept?.id
        // 中文注释：若无法识别成员所属科室，则保留该成员以避免误删
        if (memberDeptId == null) return true
        return !removedDeptIds.includes(memberDeptId)
      })
    }
  },
  { deep: true }
)

// 初始化编辑数据——读取路由中的 wardId 并进行详情回显
const initEditData = async () => {
  const wardId = route.query?.wardId
  if (!wardId) return // 无 wardId，保持新增模式

  try {
    const resp = await getWardDetail(wardId)
    if (resp?.code !== 200 || !resp?.data) {
      proxy.$modal.notifyWarning(resp?.message || '获取病区详情失败')
      return
    }

    const detail = resp.data
    // 中文注释：根据约定的结构进行数据回显，兼容字段名差异
    wardForm.wardId = detail.wardId ?? detail.id ?? String(wardId)
    wardForm.wardName = detail.baseWard?.wardName ?? detail.wardName ?? ''
    wardForm.wardLocation = detail.baseWard?.wardLocation ?? detail.wardLocation ?? ''
    // 中文注释：成员列表回显
    selectedMembers.value = Array.isArray(detail.users) ? detail.users : []

    // 中文注释：病房/病床数据回显，确保为数组
    wardForm.beds = Array.isArray(detail.wardRooms) && detail.wardRooms.length > 0 ? detail.wardRooms : wardForm.beds

    // 中文注释：回显关联科室（字符串"1,2,3"或数组 [1,2,3] 均兼容）
    const depts = detail.deptIds ?? detail.baseWard?.deptIds
    if (Array.isArray(depts)) {
      selectedDepartments.value = depts
    } else if (typeof depts === 'string' && depts.trim()) {
      selectedDepartments.value = depts
        .split(',')
        .map(s => s.trim())
        .filter(Boolean)
    }
  } catch (e) {
    console.error('加载病区详情异常：', e)
    proxy.$modal.notifyWarning('加载病区详情失败')
  }
}
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.module.scss' as *;

// 关键帧动画定义
@keyframes memberTagFadeIn {
  0% {
    opacity: 0;
    transform: translateY(10px) scale(0.9);
  }
  50% {
    opacity: 0.7;
    transform: translateY(-2px) scale(1.05);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes ripple {
  0% {
    transform: scale(0);
    opacity: 1;
  }
  100% {
    transform: scale(4);
    opacity: 0;
  }
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.ward-add-form {
  .form-container {
    .form-card {
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

      :deep(.el-card__header) {
        background-color: #f8f9fa;
        border-bottom: 2px solid #e4e7ed;

        .card-title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }

      .ward-form {
        .section-title {
          font-size: 14px;
          font-weight: 600;
          color: #303133;
          margin: 24px 0 16px 0;
          padding-bottom: 8px;
          border-bottom: 1px solid #e4e7ed;
        }

        .member-section {
          .member-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;

            .member-label {
              font-size: 14px;
              color: #606266;
            }

            .add-member-btn {
              background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
              border: none;
              border-radius: 4px;
              padding: 6px 12px;
              font-size: 12px;
            }
          }

          .member-empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
            background: #fafbfc;
            border: 2px dashed #d9d9d9;
            border-radius: 8px;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            cursor: pointer;
            position: relative;
            overflow: hidden;

            // 添加点击波纹效果
            &::before {
              content: '';
              position: absolute;
              top: 50%;
              left: 50%;
              width: 0;
              height: 0;
              background: rgba(64, 158, 255, 0.1);
              border-radius: 50%;
              transform: translate(-50%, -50%);
              transition: all 0.6s ease;
            }

            &:hover {
              border-color: #409eff;
              background: linear-gradient(135deg, #f0f8ff 0%, #e6f4ff 100%);
              transform: translateY(-2px);
              box-shadow: 0 8px 25px rgba(64, 158, 255, 0.15);

              .empty-icon {
                transform: scale(1.1) rotate(5deg);
                color: #409eff;
              }

              .empty-title {
                color: #409eff;
              }
            }

            &:active {
              transform: translateY(0);
              box-shadow: 0 4px 15px rgba(64, 158, 255, 0.2);

              &::before {
                width: 300px;
                height: 300px;
              }
            }

            .empty-icon {
              margin-bottom: 16px;
              transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            }

            .empty-text {
              text-align: center;
              transition: all 0.3s ease;

              .empty-title {
                color: #909399;
                font-size: 14px;
                margin-bottom: 8px;
                transition: color 0.3s ease;
              }

              .empty-desc {
                color: #c0c4cc;
                font-size: 12px;
                margin: 0;
                transition: color 0.3s ease;
              }
            }
          }

          .selected-members {
            // 确保与empty-state高度一致
            min-height: 140px;

            .selected-header {
              margin-bottom: 16px;

              .selected-count {
                font-size: 14px;
                color: #409eff;
                background: #f0f8ff;
                padding: 4px 12px;
                border-radius: 12px;
              }
            }

            .selected-list-container {
              // 固定高度，与empty-state保持一致
              height: 120px;
              background: #fafbfc;
              border: 1px solid #e4e7ed;
              border-radius: 8px;
              padding: 12px;
              overflow-y: auto;

              // 自定义滚动条样式
              &::-webkit-scrollbar {
                width: 6px;
              }

              &::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 3px;
              }

              &::-webkit-scrollbar-thumb {
                background: #c1c1c1;
                border-radius: 3px;
                transition: background 0.3s ease;

                &:hover {
                  background: #a8a8a8;
                }
              }

              .selected-list {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
                gap: 8px;
                align-content: start;

                // 响应式网格布局
                @media (min-width: 1920px) {
                  grid-template-columns: repeat(8, 1fr); // 超大屏：8列
                }

                @media (min-width: 1440px) and (max-width: 1919px) {
                  grid-template-columns: repeat(7, 1fr); // 大屏：7列
                }

                @media (min-width: 1200px) and (max-width: 1439px) {
                  grid-template-columns: repeat(6, 1fr); // 中大屏：6列
                }

                @media (min-width: 992px) and (max-width: 1199px) {
                  grid-template-columns: repeat(5, 1fr); // 中屏：5列
                }

                @media (min-width: 768px) and (max-width: 991px) {
                  grid-template-columns: repeat(4, 1fr); // 小屏：4列
                }

                @media (min-width: 576px) and (max-width: 767px) {
                  grid-template-columns: repeat(3, 1fr); // 超小屏：3列
                  gap: 6px;
                }

                @media (max-width: 575px) {
                  grid-template-columns: repeat(2, 1fr); // 手机：2列
                  gap: 4px;
                }

                .selected-member-tag {
                  display: flex;
                  align-items: center;
                  padding: 6px 8px;
                  background: #ffffff;
                  border: 1px solid #d9d9d9;
                  border-radius: 16px;
                  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
                  cursor: default;
                  min-height: 32px;
                  position: relative;
                  overflow: hidden;
                  // 添加进入动画
                  animation: memberTagFadeIn 0.5s ease-out;
                  // 响应式调整
                  @media (max-width: 767px) {
                    padding: 4px 6px;
                    min-height: 28px;
                    border-radius: 14px;
                  }

                  @media (max-width: 575px) {
                    padding: 3px 5px;
                    min-height: 24px;
                    border-radius: 12px;
                  }

                  // 添加背景渐变效果
                  &::before {
                    content: '';
                    position: absolute;
                    top: 0;
                    left: -100%;
                    width: 100%;
                    height: 100%;
                    background: linear-gradient(90deg, transparent, rgba(64, 158, 255, 0.1), transparent);
                    transition: left 0.6s ease;
                  }

                  &:hover {
                    border-color: #409eff;
                    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
                    transform: translateY(-2px) scale(1.02);
                    background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);

                    &::before {
                      left: 100%;
                    }

                    .remove-btn {
                      opacity: 1;
                      transform: scale(1.1);
                    }

                    .member-avatar {
                      transform: scale(1.1);
                      background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);

                      .el-icon {
                        color: white !important;
                      }
                    }
                  }

                  &:active {
                    transform: translateY(0) scale(0.98);
                    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
                  }

                  .member-avatar {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 20px;
                    height: 20px;
                    background: #f0f8ff;
                    border-radius: 50%;
                    margin-right: 6px;
                    flex-shrink: 0;
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

                    // 响应式调整
                    @media (max-width: 767px) {
                      width: 18px;
                      height: 18px;
                      margin-right: 4px;
                    }

                    @media (max-width: 575px) {
                      width: 16px;
                      height: 16px;
                      margin-right: 3px;
                    }
                  }

                  .member-info {
                    flex: 1;
                    min-width: 0; // 允许文本截断

                    .member-name {
                      font-size: 12px;
                      font-weight: 500;
                      color: #303133;
                      line-height: 1.2;
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      transition: color 0.3s ease;

                      // 响应式调整
                      @media (max-width: 767px) {
                        font-size: 11px;
                      }

                      @media (max-width: 575px) {
                        font-size: 10px;
                      }
                    }

                    .member-details {
                      font-size: 10px;
                      color: #909399;
                      line-height: 1.2;
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      margin-top: 1px;
                      transition: color 0.3s ease;

                      // 响应式调整
                      @media (max-width: 767px) {
                        font-size: 9px;
                      }

                      @media (max-width: 575px) {
                        display: none; // 手机端隐藏详细信息
                      }
                    }
                  }

                  .remove-btn {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 16px;
                    height: 16px;
                    margin-left: 4px;
                    cursor: pointer;
                    border-radius: 50%;
                    opacity: 0.7;
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    flex-shrink: 0;

                    // 响应式调整
                    @media (max-width: 767px) {
                      width: 14px;
                      height: 14px;
                      margin-left: 3px;
                    }

                    @media (max-width: 575px) {
                      width: 12px;
                      height: 12px;
                      margin-left: 2px;
                    }

                    &:hover {
                      background: linear-gradient(135deg, #fef0f0 0%, #fde2e2 100%);
                      opacity: 1;
                      transform: scale(1.2);

                      .el-icon {
                        color: #f56c6c !important;
                      }
                    }

                    &:active {
                      transform: scale(0.9);
                    }
                  }
                }
              }
            }

            .add-more-section {
              margin-top: 12px;
              text-align: center;

              .add-more-btn {
                border-radius: 16px;
                padding: 6px 16px;
                font-size: 12px;
                transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
                position: relative;
                overflow: hidden;

                // 响应式调整
                @media (max-width: 767px) {
                  padding: 4px 12px;
                  font-size: 11px;
                  border-radius: 14px;
                }

                @media (max-width: 575px) {
                  padding: 3px 8px;
                  font-size: 10px;
                  border-radius: 12px;
                }

                // 添加背景动画效果
                &::before {
                  content: '';
                  position: absolute;
                  top: 0;
                  left: -100%;
                  width: 100%;
                  height: 100%;
                  background: linear-gradient(90deg, transparent, rgba(64, 158, 255, 0.05), transparent);
                  transition: left 0.8s ease;
                }

                &:hover {
                  background: linear-gradient(135deg, #f0f8ff 0%, #f8fbff 100%);
                  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
                  transform: translateY(-2px) scale(1.02);

                  &::before {
                    left: 100%;
                  }

                  .el-icon {
                    color: #409eff !important;
                    transform: rotate(90deg) scale(1.2);
                  }
                }

                &:active {
                  transform: translateY(0) scale(0.98);
                  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
                }

                .el-icon {
                  margin-right: 4px;
                  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

                  // 响应式调整
                  @media (max-width: 575px) {
                    margin-right: 2px;
                  }
                }
              }
            }
          }
        }

        // 成员选择弹窗样式已提取至组件样式模块

        .bed-section {
          .bed-table {
            .charge-items-cell {
              display: flex;
              flex-direction: column;
              gap: 8px;
              align-items: center;
              cursor: pointer;
              padding: 8px;
              border-radius: 4px;
              transition: background-color 0.2s ease;
              min-height: 40px;
              justify-content: center;
              position: relative;

              &:hover {
                background-color: #f5f7fa;
              }

              .selected-items {
                display: flex;
                flex-wrap: wrap;
                gap: 4px;
                justify-content: center;
                max-width: 100%;
                pointer-events: none; // 防止子元素阻止点击事件

                .charge-item-tag {
                  font-size: 12px;
                  max-width: 120px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  pointer-events: none; // 防止标签阻止点击事件
                }
              }

              .select-charge-btn {
                font-size: 12px;
                padding: 4px 8px;
                height: 24px;
              }

              .empty-state {
                display: flex;
                align-items: center;
                justify-content: center;
                min-height: 32px;

                .empty-text {
                  color: #909399;
                  font-size: 12px;
                  user-select: none;
                }
              }
            }

            // 床号显示样式
            .bed-numbers-display {
              display: flex;
              gap: 4px;
              justify-content: flex-start;
              align-items: center;
              min-height: 32px;
              padding: 4px;
              width: 100%;
              cursor: pointer;
              max-width: 100%;
              overflow: hidden;
              position: relative;

              // 当床号过多时，添加渐变遮罩效果
              &::after {
                content: '';
                position: absolute;
                right: 0;
                top: 0;
                bottom: 0;
                width: 20px;
                background: linear-gradient(to right, transparent, #fff);
                pointer-events: none;
                opacity: 0;
                transition: opacity 0.3s ease;
              }

              // 当内容溢出时显示遮罩
              &.overflow::after {
                opacity: 1;
              }

              .bed-number-tag {
                font-size: 12px;
                background-color: #e1f3d8;
                border-color: #67c23a;
                color: #67c23a;
                margin: 2px;
                flex-shrink: 0;
                white-space: nowrap;
                max-width: 60px;
                overflow: hidden;
                text-overflow: ellipsis;
              }

              .empty-bed-numbers {
                color: #c0c4cc;
                font-size: 12px;
                font-style: italic;
              }

              // 添加悬停时的滚动效果
              &:hover {
                overflow-x: auto;
                overflow-y: hidden;

                &::-webkit-scrollbar {
                  height: 4px;
                }

                &::-webkit-scrollbar-track {
                  background: #f1f1f1;
                  border-radius: 2px;
                }

                &::-webkit-scrollbar-thumb {
                  background: #c1c1c1;
                  border-radius: 2px;

                  &:hover {
                    background: #a8a8a8;
                  }
                }
              }
            }

            .total-amount {
              font-weight: 600;
              color: #409eff;
            }

            .remove-btn {
              &:disabled {
                opacity: 0.5;
                cursor: not-allowed;
              }
            }
          }

          .add-bed-section {
            margin-top: 16px;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            .add-bed-btn {
              padding: 8px 24px;
              font-size: 14px;
              border-radius: 6px;
              transition: all 0.3s ease;

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
              }

              &:active {
                transform: translateY(0);
              }
            }
          }
        }

        // 收费项目弹窗样式已提取至组件样式模块
        .bed-section {
          .bed-table {
            border-radius: 6px;

            /* 删除列去除省略号：避免按钮后出现“...” */
            :deep(.no-ellipsis .cell) {
              text-overflow: clip; /* 关闭省略号显示 */
              overflow: visible; /* 允许内容正常溢出（此处仅按钮） */
              white-space: nowrap; /* 保持单行，避免高度抖动 */
            }

            :deep(.el-table__header) {
              background-color: #f8f9fa;

              th {
                background-color: #f8f9fa !important;
                color: #606266;
                font-weight: 600;
                font-size: 13px;
              }
            }
          }
        }
      }
    }
  }
}

// 统一的“点击设置”悬浮提示样式
.hover-editable {
  cursor: pointer;
  position: relative;
}

.hover-editable:hover::before {
  content: '点击设置';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  font-size: 12px;
  color: #333;
  background: #fff;
  border-radius: 4px;
  pointer-events: none;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

// 响应式设计
@media (max-width: 768px) {
  .ward-add-form {
    padding: 16px;

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .header-left {
        .page-title {
          font-size: 20px;
        }
      }

      .header-right {
        width: 100%;

        .default-btn {
          width: 100%;
          justify-content: center;
        }
      }
    }

    .form-container {
      .ward-form {
        .member-section {
          .member-item {
            :deep(.el-row) {
              flex-direction: column;
              gap: 12px;

              .el-col {
                width: 100% !important;
                max-width: 100% !important;
              }
            }
          }
        }

        .bed-section {
          overflow-x: auto;

          .bed-table {
            min-width: 800px;
          }
        }

        .form-actions {
          flex-direction: column;

          .cancel-btn,
          .submit-btn {
            width: 100%;
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .ward-add-form {
    padding: 12px;

    .page-header {
      .header-left {
        .page-title {
          font-size: 18px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
/* 床位数下拉选项栅格化：一行四列 */
.bed-count-dropdown .el-select-dropdown__list {
  display: grid; /* 使用网格布局 */
  grid-template-columns: repeat(5, minmax(0, 1fr)); /* 五列自适应 */
  gap: 6px; /* 选项间距 */
  padding: 8px; /* 适当内边距 */
}

.bed-count-dropdown .el-select-dropdown__item {
  margin: 0; /* 去除默认外边距，避免布局错乱 */
  display: flex; /* 中心对齐文本 */
  align-items: center;
  justify-content: center;
  white-space: nowrap; /* 选项文案不换行，避免高度不一致 */
}
</style>
